<template>
    <div  >
        <el-upload
            :action="CMBASE.baseUploadAction"
            accept="image/jpeg,image/gif,image/png"
            :limit="limit"
            :on-exceed="uploadOverRun"
            :on-success="handleSuccess"
            :on-remove="handleRemove"
            :on-preview="handlePictureCardPreview"
            :on-error="handleError"
            :file-list="fileList"
            multiple
            list-type="picture-card"
            class="app-uploader"
        >
            <i class="el-icon-plus"/>
        </el-upload>
        <el-dialog
            :visible.sync="dialogVisible"
            width="33%"
        >
            <img style="width: 100%;height: 100%;object-fit: contain" :src="dialogImageUrl" alt="">
        </el-dialog>
    </div>
</template>
<script>
export default {
    props: {
        value: {
            type: String
        },
        limit: {
            type: Number,
            default: 8
        }
    },
    data() {
        return {
            dialogImageUrl: '',
            dialogVisible: false,
            images: [],
            _value: [],
            fileList: []
        }
    },
    watch:{
        value(newValue, oldValue) {
            this._value = newValue !== '' && newValue.split(',')
            this.fileList = this._value.map((item) => ({url: this.CMBASE.baseFileContext + item}))
        }
    },
    mounted() {
        this._value = this.value !== '' && this.value.split(',')
        this.fileList = this._value.map((item) => ({url: this.CMBASE.baseFileContext + item}))
    },
    methods: {
        /* 多图上传预览 */
        handlePictureCardPreview(file) {
            this.dialogImageUrl = file.url
            this.dialogVisible = true
        },
        /* 多图上传限制 */
        uploadOverRun() {
            this.$message({
                type: 'error',
                // message: '上传文件个数超出限制!最多上传8张图片!'
                message: '上传文件个数超出限制!最多上传'+this.limit+'张图片!'
            })
        },
        /* 多图上传移除 */
        handleRemove(file, fileList) {

            let valueList = this.value.split(",")
            for (var i = 0; i < valueList.length; i++) {
                // 存在两种情况
                // 1. 如果所删除图片是刚刚上传的图片，那么图片地址是file.response.data.url
                //    此时的file.url虽然存在，但是是本机地址，而不是远程地址。
                // 2. 如果所删除图片是后台返回的已有图片，那么图片地址是file.url
                let url
                // 后台已有照片
                if (file.response === undefined) {
                    url = file.url
                } else {
                    url = file.response.path
                }
                if (url.includes(valueList[i])) {
                    valueList.splice(i, 1)
                }
            }

            this.$emit('input', valueList.join(','))
        },
        // 上传错误时的钩子
        handleError() {
            this.$message({message: '上传失败', type: 'error'})
        },
        /* 文件上传成功 */
        handleSuccess(res, fileList) {
            try {
                if (res.state === 'success') {
                    // this.$emit('input', [...(this.value.split(",")), res.path].join(","))
                    if(res.path){
                        let str = [...(this.value.split(",")), res.path].join(",")
                        //如果第一个有逗号，就截取，如果没有，就不截取
                        if(str.substring(0,1) === ','){
                            str = str.substr(1)
                        }else{
                            str = str
                        }
                        this.$emit('input', str)
                    }
                } else {
                    this.$message.error(res.msg + '上传失败请稍后重试！')
                }
            } catch (e) {
                console.log(e)
            }
        }
    }
}
</script>
<style>
.el-upload-list {
    display: flex;
}
</style>
